#!/data/Software/mydan/perl/bin/perl -I/data/Software/mydan/JOB/lib -I/data/Software/mydan/JOB/private/lib
use strict;
use warnings;
use uuid;
use keepalive;
use Logs;

$| ++;

=head1 SYNOPSIS

    db => $mysql,
    id => 1,

=cut

return sub
{
    my %param = @_;
    my ( $db, $id ) = @param{qw(db id)};

    my $logs = Logs->new( 'crontask' );

    $logs->die( "id not a number" ) unless $id =~ /^\d+$/;

    my $slave = eval{ keepalive->new( $db )->slave() };
    $logs->die( "get slave error: $@" ) if $@;
    $logs->die( "nofind any slave" ) unless defined $slave;

	my $x = eval{ $db->query( "select jobs.name,jobs.projectid,crontab.jobuuid,crontab.mutex,crontab.edit_user 
        from crontab,jobs where jobs.uuid=crontab.jobuuid and crontab.id='$id'" ); };
    $logs->die( "get jobs info from mysql fail: $@" ) if $@;
    $logs->die( "get jobs info from mysql fail" ) unless defined $x && ref $x eq 'ARRAY';
	$logs->die( "crontab id is illegal, mismatch: $id" ) unless @$x;

    my ( $name, $projectid,$jobuuid, $mutex, $edit_user ) = @{$x->[0]}; 

    $mutex ||= '';
    my $uuid = uuid->new()->create_str;

    my $timeid = int( ( time + 5 ) / 60 );
    eval{ $db->execute( "insert into crontablock (`crontabid`,`timeid` )values( '$id', '$timeid' )" );};
    if( $@ )
    {
        my $tmperror = $@;
        if( $tmperror =~ /Duplicate entry/ )
        {
            $logs->say( "crontab task $id doesn't belong to me" );
            return;
        }
        else
        {
            $logs->die( "insert into crntablock error: $tmperror" );
        }
    }

    eval{ $db->execute( 
        "insert into task (`projectid`,`uuid`,`name`,`user`,`slave`,`status`,`calltype`,`jobtype`,`jobuuid`,`mutex`) 
            values('$projectid','$uuid','$name','$edit_user','$slave', 'init','crontab','jobs','$jobuuid','$mutex')" 
    );};

    $logs->die( "create a task fail: crontabid=$id, projectid=$projectid" ) if $@;
}
